package com.wsx.ones.gateway.remote.netty;

import com.wsx.ones.gateway.core.config.RouterConfig;
import com.wsx.ones.gateway.utils.ConnetUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangshuaixin
 * @Title: com.wsx.ones.gateway.remote.netty.NettyServerHandler
 * @Description: TODO
 * @date 2019/07/17
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static Logger log = LogManager.getLogger(NettyServerHandler.class);

    private NettyServerConfig nettyServerConfig;
    private RouterConfig routerConfig;
    private ConcurrentHashMap<String, Channel> channels;

    public NettyServerHandler(NettyServerConfig nettyServerConfig,
                              RouterConfig routerConfig) {
        this.nettyServerConfig = nettyServerConfig;
        this.routerConfig = routerConfig;
        int max = (int)(nettyServerConfig.getMaxChannels()/0.75) + 1;
        this.channels = new ConcurrentHashMap<>(max);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        if (channels.size() >= nettyServerConfig.getMaxChannels()) {
            log.warn("channels is arrive max ");
            channel.close();
        } else {
            String key = ConnetUtils.generateKey(channel.remoteAddress(), channel.localAddress());
            channels.put(key, channel);
            super.channelRegistered(ctx);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
        String uri = fullHttpRequest.uri();
        HttpMethod httpMethod = fullHttpRequest.method();
        HttpHeaders httpHeaders = fullHttpRequest.headers();
        ByteBuf body = fullHttpRequest.content();

        System.out.print(uri + "===" + httpMethod.toString() + "===" );
        channelHandlerContext.writeAndFlush("hello world");
    }
}
